package com.tengju.bff.interfaces.covercharge.controller.portal;

import com.alibaba.fastjson.JSON;
import com.idanchuang.component.base.JsonResult;
import com.idanchuang.component.redis.util.DRedisLocks;
import com.tengju.bff.interfaces.covercharge.constant.BizConstants;
import com.tengju.bff.interfaces.covercharge.constant.CoverChargeEnum;
import com.tengju.bff.interfaces.covercharge.constant.CoverChargeErrorCode;
import com.tengju.bff.interfaces.covercharge.entity.vo.AccountUnbind;
import com.tengju.bff.interfaces.covercharge.service.IServiceBankService;
import com.tengju.bff.interfaces.covercharge.util.UserUtils;
import com.tengju.bff.interfaces.shared.ApiResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Controller
@Slf4j
@RequestMapping("/api/account")
@Api(value = "account", tags = "账户")
public class AccountController {

    @Autowired
    private IServiceBankService serviceBankService;

    @PostMapping("/unbind")
    @ResponseBody
    @ApiOperation(value = "解绑收款账户")
    public ApiResponse<?> unbind(HttpServletRequest request, @RequestBody AccountUnbind accountUnbind) {
        log.info("解绑收款账户...{}", JSON.toJSONString(accountUnbind));

        accountUnbind.setFrom(UserUtils.getPlatFrom(request));
        Assert.hasText(accountUnbind.getCheckCode(), "短信验证码不能为空");

        //账户类型
        CoverChargeEnum.ServiceAccountType accountType = CoverChargeEnum.ServiceAccountType.MANAGE_TYPE;

        Integer idCode = UserUtils.getIdCode(request);
        Integer userId = UserUtils.getUserId(request);

        return DRedisLocks.runWithLock(BizConstants.ACCOUNT_UNBIND + idCode, 500, () -> {
            try {
                serviceBankService.unbind(accountType, userId, idCode, accountUnbind.getCheckCode());
                return ApiResponse.newSuccess();
            } catch (Exception e) {
                log.error("account unbind error", e);
                return ApiResponse.newFailure(CoverChargeErrorCode.SYS_ERROR.getCode(), e.getMessage());
            }
        });
    }

}
